import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

public class Servlet5 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies=req.getCookies();
        int len=0;
        String lastTime=null;
        if(cookies!=null) len=cookies.length;
        for (int i = 0; i < len; i++) {
            if(cookies[i].getName().equals("lastAccess")){
                lastTime=cookies[i].getValue();
                lastTime= URLDecoder.decode(lastTime,"UTF-8");
                System.out.println("该浏览器上一次访问本servlet的时间是："+lastTime);
                break;
            }
        }
        resp.setContentType("text/html;charset=utf-8");
        if(lastTime!=null){//浏览器不是第一次访问
            resp.getWriter().write("你上一次访问本servlet的时间是："+lastTime);
        }else {
            resp.getWriter().write("你是第一次访问本网站！");
        }
        //接下来的代码是在响应消息包头部携带cookie信息，浏览器接收到就会保存
        Date nowTime=new Date();
        String strNow=nowTime.toString();
        strNow=URLEncoder.encode(strNow,"UTF-8");
        System.out.println(strNow);
        Cookie cookie=new Cookie("lastAccess",strNow);
        cookie.setMaxAge(10);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
